import subprocess
import sys
import os
import os.path
import json

def read_config():
    """Read and parse the config.json file"""
    config_path = os.path.join(os.path.dirname(__file__), 'config.json')
    try:
        with open(config_path, 'r') as f:
            return json.load(f)
    except FileNotFoundError:
        print(f"Config file not found at {config_path}")
        return {}
    except json.JSONDecodeError:
        print(f"Invalid JSON in config file at {config_path}")
        return {}

def main():
    # 读取配置
    config = read_config()

    # 获取当前脚本所在目录
    current_dir = os.path.dirname(os.path.abspath(__file__))
    
    # 设置参数
    app_file = config["app_url"]
    package_name = config["package_name"]
    sign_url = config["sign_url"]

    exe_path = os.path.realpath(os.path.dirname(sys.argv[0]))

    # 构建ohos-app-install.py的完整路径
    installer_script = os.path.join(current_dir, "ohos-app-install.py")
    
    # 检查安装脚本是否存在
    if not os.path.exists(installer_script):
        print(f"错误: 安装脚本不存在 -> {installer_script}")
        sys.exit(1)
    
#     # 检查app文件是否存在
#     app_path = os.path.join(current_dir, app_file)
#     if not os.path.exists(app_path):
#         print(f"错误: APP文件不存在 -> {app_path}")
#         sys.exit(1)
    
    # 根据操作系统类型选择Python命令
    python_cmd = "python" if sys.platform == "win32" else "python3"
    
    # 构建命令
    command = [
        python_cmd,
        installer_script,
        package_name,
        app_file,
        sign_url,
        exe_path
    ]
        
    # 执行命令
    try:
        subprocess.run(command, check=True)
        print("安装完成")
        if sys.platform.startswith('win'):
            input("按回车键退出...")
    except subprocess.CalledProcessError as e:
        print(f"安装失败: {str(e)}")
        if sys.platform.startswith('win'):
            input("按回车键退出...")
        sys.exit(1)

if __name__ == "__main__":
    main()